#target illustrator
(function () {
    if (app.documents.length === 0) { alert("请先打开文档"); return; }
    var sel = app.activeDocument.selection;
    if (!sel || sel.length === 0) { alert("请先选择文字对象（TextFrame）"); return; }

    // ==== ScriptUI 面板 ====
    var dlg = new Window("dialog", "文字对齐调整");
    dlg.orientation = "column";
    dlg.alignChildren = ["fill", "top"];
    dlg.margins = 12;

    var info = dlg.add("statictext", undefined, "选择要应用的对齐方式：");
    info.alignment = "left";

    var grp = dlg.add("panel", undefined, "对齐方式");
    grp.orientation = "column";
    grp.alignChildren = ["left", "top"];
    grp.margins = 12;

    var rbLeft   = grp.add("radiobutton", undefined, "左对齐");
    var rbCenter = grp.add("radiobutton", undefined, "居中对齐");
    var rbRight  = grp.add("radiobutton", undefined, "右对齐");
    rbCenter.value = true; // 默认居中

    var btnRow = dlg.add("group");
    btnRow.alignment = "right";
    var okBtn = btnRow.add("button", undefined, "确定", { name: "ok" });
    var cancelBtn = btnRow.add("button", undefined, "取消", { name: "cancel" });

    var result = dlg.show();
    if (result !== 1) return; // 用户取消

    // 映射选择到 Justification
    var justi = Justification.CENTER;
    if (rbLeft.value) justi = Justification.LEFT;
    else if (rbRight.value) justi = Justification.RIGHT;

    // ==== 核心处理：逐段设置 + 位置补偿（基于 position 差值） ====
    var changedCount = 0;

    for (var i = 0; i < sel.length; i++) {
        var tf = sel[i];
        if (tf.typename !== "TextFrame") continue;
        if (tf.locked || tf.hidden) continue;

        // 记录修改前位置（position = [left, top]）
        var oldPos = [tf.position[0], tf.position[1]];

        // 逐段设置：在你的环境中已验证最可靠
        try {
            var pc = tf.paragraphs.length; // 点文字也 >= 1
            for (var p = 0; p < pc; p++) {
                try { tf.paragraphs[p].justification = justi; } catch (_) {}
            }
        } catch (_) {}

        // 兜底：整段段落属性
        try { tf.textRange.paragraphAttributes.justification = justi; } catch (_) {}

        // 位置补偿：仅按 position 的变化回搬，避免 bounds 导致的误差
        var newPos = tf.position;
        var dx = oldPos[0] - newPos[0];
        var dy = oldPos[1] - newPos[1];
        if (dx !== 0 || dy !== 0) {
            try { tf.translate(dx, dy); } catch (_) {}
        }

        changedCount++;
    }

    app.redraw();

    if (changedCount === 0) {
        alert("未发现可处理的文字对象（可能已锁定/隐藏或选区非文字）。");
    }
})();
